package com.mogujie.tt.ui.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.mogujie.tt.DB.DBInterface;
import com.mogujie.tt.DB.entity.DepartmentEntity;
import com.mogujie.tt.DB.entity.GroupEntity;
import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.R;
import com.mogujie.tt.config.NewFriendsConstant;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.imservice.event.GroupEvent;
import com.mogujie.tt.imservice.event.UserInfoEvent;
import com.mogujie.tt.imservice.manager.IMContactManager;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.ui.activity.ChatRoomActivity;
import com.mogujie.tt.ui.activity.DepartmentActivity;
import com.mogujie.tt.ui.activity.DepartmentTwoActivity;
import com.mogujie.tt.ui.activity.NewFriendsActivity;
import com.mogujie.tt.ui.adapter.ContactAdapter;

import com.mogujie.tt.ui.widget.SortSideBar;
import com.mogujie.tt.ui.widget.SortSideBar.OnTouchingLetterChangedListener;
import com.mogujie.tt.utils.FileUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import de.greenrobot.event.EventBus;

/**
 * 联系人列表页
 * 
 */

public class FragmentFriends extends MainFragment  implements OnTouchingLetterChangedListener {

    private View curView = null;
    private boolean hidden;


    private LayoutInflater infalter;

    private ContactAdapter contactAdapter;

    private IMService imService;
    private IMContactManager contactMgr;



    //通讯录列表更新
    private ListView allContactListView;//显示好友
    private SortSideBar sortSideBar;
    private TextView dialog;
    private DBInterface dbInterface = DBInterface.instance();
    private Map<Integer,DepartmentEntity> departmentMap = new ConcurrentHashMap<>();//根据部门ID 得到部门名
    /**
     * 查询通讯录服务
     */
    private IMServiceConnector imServiceConnector = new IMServiceConnector() {
        @Override
        public void onIMServiceConnected() {
            logger.d("contactUI#onIMServiceConnected");

            imService = imServiceConnector.getIMService();
            if (imService == null) {
                logger.e("ContactFragment#onIMServiceConnected# imservice is null!!");
                return;
            }
            contactMgr = imService.getContactManager();

            // 初始化视图
        //    initAdapter();
            renderEntityList();//查询视图
            EventBus.getDefault().registerSticky(FragmentFriends.this);
        }

        @Override
        public void onServiceDisconnected() {
            if (EventBus.getDefault().isRegistered(FragmentFriends.this)) {
                EventBus.getDefault().unregister(FragmentFriends.this);
            }
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imServiceConnector.connect(getActivity());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(FragmentFriends.this)) {
            EventBus.getDefault().unregister(FragmentFriends.this);
        }
        imServiceConnector.disconnect(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        if (null != curView) {
            ((ViewGroup) curView.getParent()).removeView(curView);
            return curView;
        }
        curView = inflater.inflate(R.layout.fragment_contactlist, topContentView);
        initRes();
        return curView;
    }

    /**
     * @Description 初始化界面资源
     */
    private void initRes() {
        // 设置顶部标题栏
        initTitleView();
        super.init(curView);
        showProgressBar();

        sortSideBar = (SortSideBar) curView.findViewById(R.id.sidrbar);
        dialog = (TextView) curView.findViewById(R.id.dialog);
        sortSideBar.setTextView(dialog);
        sortSideBar.setOnTouchingLetterChangedListener(this);

        allContactListView = (ListView) curView.findViewById(R.id.all_contact_list);//显示所有好友
       allContactListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true));//滑动所有好友

    }

    private void initAdapter(){
        contactAdapter = new ContactAdapter(getActivity(),imService);

        allContactListView.setAdapter(contactAdapter);
        // 单击视图事件
        allContactListView.setOnItemClickListener(contactAdapter);
        allContactListView.setOnItemLongClickListener(contactAdapter);
    }

    /**
     * @Description 设置顶部
     */
    private void initTitleView() {
        // 设置标题
        setTopTitleBold("通讯录");
        setTopRightButton(R.drawable.ty_btn_jty);
    }


    @Override
    protected void initHandler() {

    }

    RelativeLayout re_chatroom;
    TextView tv_unread;
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        infalter=LayoutInflater.from(getActivity());
        View headView = infalter.inflate(R.layout.item_contact_list_header, null);
        allContactListView.addHeaderView(headView,null,false);//设置没有Item点击事件

        initAdapter();
        RelativeLayout re_newfriends=(RelativeLayout) headView.findViewById(R.id.re_newfriends);
        tv_unread =(TextView)re_newfriends.findViewById(R.id.tv_unread);//设置
         re_chatroom=(RelativeLayout) headView.findViewById(R.id.re_chatroom);
        re_newfriends.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                      startActivity(new Intent(getActivity(),NewFriendsActivity.class));
            //    Toast.makeText(getActivity(), "新朋友", Toast.LENGTH_SHORT).show();
            }

        });
        re_chatroom.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), DepartmentTwoActivity.class));
                //      Toast.makeText(getActivity(),"聊天",Toast.LENGTH_SHORT).show();
            }

        });
      RelativeLayout re_abel=(RelativeLayout) headView.findViewById(R.id.re_abel);

        re_abel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ChatRoomActivity.class));
            }
        });



    }

    /**
     * 是否显示部门
     */
    private void whetherAccordingDepartment(){
        List<DepartmentEntity> deptlist = dbInterface.loadAllDept();//加载所有子部门
        departmentMap.clear();
        for(DepartmentEntity deptInfo:deptlist){
            departmentMap.put(deptInfo.getDepartId(),deptInfo);//加载所有子部门
       //     Log.v("onActivityCreated", "deptInfo = " + deptInfo.getDepartName());
        }
      //  Log.v("onActivityCreated","LoginDeptId ="+IMLoginManager.instance().getLoginDeptId());
        if(departmentMap.get(IMLoginManager.instance().getLoginDeptId()).getDepartLevel() ==0){//部门等级为0
      //      Log.v("onActivityCreated","LoginDeptId ="+departmentMap.get(IMLoginManager.instance().getLoginDeptId()));
            re_chatroom.setVisibility(View.GONE);
        }
    }

    /**
     * 刷新单个entity
     * 很消耗性能
     */
    private void renderEntityList() {
        hideProgressBar();
        logger.d("contact#renderEntityList");

        if (contactMgr.isUserDataReady() ) {
              renderUserList();
            whetherAccordingDepartment();//是否显示部门

        }
        if (imService.getGroupManager().isGroupReady()) {
            renderGroupList();
        }
        showSearchFrameLayout();//显示搜索列表
    }




    private void renderUserList(){
        List<UserEntity> contactList = contactMgr.getFriendsListContactSortedList();//得到好友
        displayAddYourFriends();//显示有多少个好友请求添加你
        // 没有任何的联系人数据
        if (contactList.size() <= 0) {
            return;
        }
        contactAdapter.putUserList(contactList);//添加显示的人
    }


    private void renderGroupList() {
        logger.d("group#onGroupReady");
        List<GroupEntity> originList = imService.getGroupManager().getNormalGroupSortedList();
        if(originList.size() <= 0){
            return;
        }
        contactAdapter.putGroupList(originList);//分组列表
    }



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden) {
         //   refresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!hidden) {
         //   refresh();
        }
    }

    private ListView getCurListView() {
            return allContactListView;
    }
    @Override
    public void onTouchingLetterChanged(String s) {
        int position = -1;

            position =  contactAdapter.getPositionForSection(s.charAt(0));

        if (position != -1) {
            getCurListView().setSelection(position);
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }

     /**-----------事件--------------------------**/
    public void onEventMainThread(GroupEvent event) {
        switch (event.getEvent()) {
            case GROUP_INFO_UPDATED:
            case GROUP_INFO_OK:
                renderGroupList();
                searchDataReady();
                break;
        }
    }

    public void onEventMainThread(UserInfoEvent event) {
        switch (event) {
            case USER_INFO_UPDATE:
            case USER_INFO_OK:
                searchDataReady();
                whetherAccordingDepartment();//是否显示部门
                break;
            case USER_FRIEND_UPDATE:
                renderUserList();//添加好友
                break;
        }
    }

    public void searchDataReady() {
        if (imService.getContactManager().isUserDataReady() &&
                imService.getGroupManager().isGroupReady()) {
            showSearchFrameLayout();
        }
    }

    /**
     * 显示请求添加你的好友
     */
   private void displayAddYourFriends(){
   //     Log.v("FragmentFriends","NewFriendsConstant.friendRequestAdd ="+NewFriendsConstant.friendRequestAdd);
       if(NewFriendsConstant.friendRequestAdd == 0){
           tv_unread.setVisibility(View.GONE);
       }else {
           tv_unread.setVisibility(View.VISIBLE);
           tv_unread.setText(String.valueOf(NewFriendsConstant.friendRequestAdd));
       }

   }
}
